package com.qifan.energy.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.bean.JsonBean;
import com.qifan.energy.bean.result.AddressItem;
import com.qifan.energy.bean.vo.AddressAddVO;
import com.qifan.energy.R;
import com.qifan.energy.bean.result.MemberInfo;
import com.qifan.energy.global.Keys;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.GetJsonDataUtil;
import com.qifan.energy.util.GsonUtils;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ThreadUtils;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.widget.CustomTitleBar;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class AddressUpdateActivity extends BaseActivity {

    @BindView(R.id.title_layout_bar)
    CustomTitleBar titleBar;
    @BindView(R.id.name_et)
    EditText nameEt;
    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.select_area_tv)
    TextView selectAreaTv;
    @BindView(R.id.address_detail_et)
    EditText addressDetailEt;

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    /* 判断时候初始化完成 */
    private boolean isLoaded = false;
    private AddressAddVO addressAddVO = new AddressAddVO();//初始化

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_update);
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_address_update;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        /* 更改状态栏 */
        changeStatusTransparentFontBlack();

        /* 赋值UI控件 */
        AddressItem item = (AddressItem)getIntent().getSerializableExtra(Keys.UPDATE_ADDRESS_KEY);
        if (null != item) {
            titleBar.setTitleBarTitle("修改收货地址");
            //赋值模型省市区
            addressAddVO.setProvince(item.getProvince());
            addressAddVO.setCity(item.getCity());
            addressAddVO.setRegion(item.getRegion());

            nameEt.setText(item.getName());
            nameEt.setSelection(nameEt.getText().length());
            phoneEt.setText(item.getPhoneNumber());
            String tx = item.getProvince() + " " + item.getCity() + " " + item.getRegion();
            selectAreaTv.setText(tx);
            addressDetailEt.setText(item.getDetailAddress());
        }
    }

    @Override
    protected void initData() {
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                initJsonData();
                isLoaded = true;
            }
        });
    }

    @OnClick(R.id.select_area_tv)
    void onSelectAreaTvClicked(){
        if (isLoaded){
            KeyboardUtils.hideSoftInput(this);
            showPickerView();
        } else {
            ToastUtils.showShort("正在加载，稍等重试");
        }
    }

    @OnClick(R.id.save_btn)
    void onSaveBtnClicked(TextView saveBtn){
        String name = nameEt.getText().toString();
        String phone = phoneEt.getText().toString();
        String addressDetail = addressDetailEt.getText().toString();
        if (TextUtils.isEmpty(name)){
            ToastUtils.showShort("收货人必须要填写哦~");
            return;
        }
        if (TextUtils.isEmpty(phone)){
            ToastUtils.showShort("手机号不能为空哦~");
            return;
        }
        if (phone.length() < 11){
            ToastUtils.showShort("手机号格式不对哦~");
            return;
        }
        if (TextUtils.isEmpty(addressAddVO.getProvince())){
            ToastUtils.showShort("所在地区必须选择哦~");
            return;
        }
        if (TextUtils.isEmpty(addressDetail)){
            ToastUtils.showShort("详细地址不能为空哦~");
            return;
        }

        saveBtn.setEnabled(false);
        LoadingUtils.show(this);
        addressAddVO.setName(name);
        addressAddVO.setPhoneNumber(phone);
        addressAddVO.setDetailAddress(addressDetail);
        AddressItem item = (AddressItem)getIntent().getSerializableExtra(Keys.UPDATE_ADDRESS_KEY);
        if (null != item) {//更新地址接口
            addressAddVO.setMemberId(item.getMemberId());
            NetUtils.memberAddressUpdate(item.getId(),addressAddVO,new MyObserver<String>(this) {
                @Override
                public void onSuccess(String result) {
                    saveBtn.setEnabled(true);
                    LoadingUtils.hide();
                    /* 提示并跳转 */
                    ToastUtils.showShort("已修改!");
                    setResult(RESULT_OK);
                    ActivityStackUtil.finishTopActivity();
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    saveBtn.setEnabled(true);
                    LoadingUtils.hide();
                    ToastUtils.showShort(errorMsg);
                }
            });
        } else {//新增地址接口
            MemberInfo result = SharedPreferencesUtil.getData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());
            addressAddVO.setMemberId(result.getId());
            NetUtils.memberAddressAdd(addressAddVO, new MyObserver<String>(this) {
                @Override
                public void onSuccess(String result) {
                    saveBtn.setEnabled(true);
                    LoadingUtils.hide();
                    /* 提示并跳转 */
                    ToastUtils.showShort("已保存");
                    setResult(RESULT_OK);
                    ActivityStackUtil.finishTopActivity();
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    saveBtn.setEnabled(true);
                    LoadingUtils.hide();
                    ToastUtils.showShort(errorMsg);
                }
            });
        }
    }

    /* 解析本地数据 */
    private void initJsonData() {
        String JsonData = GetJsonDataUtil.getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBeans = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBeans;
        //遍历省份
        for (int i = 0; i < jsonBeans.size(); i++) {
            //该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();
            //该省的所有地区列表（第三极）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();
            //遍历该省份的所有城市
            for (int c = 0; c < jsonBeans.get(i).getCityList().size(); c++) {
                String cityName = jsonBeans.get(i).getCityList().get(c).getName();
                //添加城市
                cityList.add(cityName);
                //该城市的所有地区列表
                ArrayList<String> city_AreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBeans.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }
            /* 添加城市数据 */
            options2Items.add(cityList);
            /* 添加地区数据 */
            options3Items.add(province_AreaList);
        }
    }

    //Gson解析
    public ArrayList<JsonBean> parseData(String result) {
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = GsonUtils.getGson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    //弹出选择器
    private void showPickerView() {
        OptionsPickerView pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + " " + opt2tx + " " + opt3tx;
                //赋值省市区
                addressAddVO.setProvince(opt1tx);
                addressAddVO.setCity(opt2tx);
                addressAddVO.setRegion(opt3tx);
                //赋值UI控件
                selectAreaTv.setText(tx);
            }
        }).setTitleText("选择地区")
                .setCyclic(true, true, true)
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pickerView.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pickerView.show();
    }
}
